package at.ptasat.util;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

public class BufferingOutputStream extends OutputStream {

	private final OutputStream out;
	private byte[] buffer;
	private int size;

	public BufferingOutputStream(OutputStream out) {
		if (out == null) {
			throw new NullPointerException();
		}
		this.out = out;
		buffer = new byte[1024];
		size = 0;
	}

	private void ensureCapacity(int capacity) {
		if (buffer.length < capacity) {
			buffer = Arrays.copyOf(buffer, buffer.length * 2);
		}
	}

	@Override
	public void write(int b) {
		write((byte) b);
	}

	public void write(byte b) {
		ensureCapacity(size + 1);
		buffer[size++] = b;
	}

	@Override
	public void flush() throws IOException {
		out.write(buffer, 0, size);
		size = 0;
		out.flush();
	}
	
	@Override
	public void close() throws IOException {
		flush();
		out.close();
	}

}
